import { useDynamicList } from 'ahooks'
import { Button, Icon, Input, Row } from 'antd'
import React, { forwardRef, useEffect } from 'react'

function valueRenderFunction({ disabled, value, onChange, valueType }) {
  return (
    <Input
      disabled={disabled}
      value={valueType === 'object' ? JSON.stringify(value) : value}
      onChange={e => onChange(valueType === 'object' ? JSON.parse(e.target.value) : e.target.value)}
      placeholder="VALUE"
    />
  )
}

function mapToList(map) {
  return Object.keys(map).map(key => ({ key, value: map[key] }))
}

function listToMap(list) {
  return list.reduce((acc, { key, value }) => {
    if (key)
      acc[key] = value

    return acc
  }, {})
}

function DynamicKeyValuePairs({
  value = {},
  onChange,
  disabled,
  renderValueComponent = valueRenderFunction,
  layout = { label: 1, value: 1 },
}) {
  const { list, remove, getKey, replace, push } = useDynamicList(mapToList(value))

  useEffect(() => {
    onChange(listToMap(list))
  }, [list, onChange])

  const Pair = (index, item) => (
    <Row
      key={getKey(index)}
      gutter={16}
      style={{ marginBottom: '8px', display: 'flex', alignItems: 'center', paddingLeft: 8 }}
    >
      <div className="margin-right" style={{ flex: layout.label }}>
        <Input
          disabled={disabled}
          value={item.key}
          onChange={e => replace(index, { ...item, key: e.target.value })}
          placeholder="KEY"
        />
      </div>
      <div className="margin-right" style={{ flex: layout.value }}>
        {renderValueComponent({
          disabled,
          value: item.value,
          onChange: value => replace(index, { ...item, value }),
          valueType: typeof item.value,
        })}
      </div>
      <div style={{ flexBasis: 27, display: 'flex', alignItems: 'center' }}>
        <Icon
          style={{
            fontSize: '16.5px',
            color: '#999',
            transition: 'all 0.3s',
          }}
          onClick={() => remove(index)}
          type="minus-circle"
        />
      </div>
    </Row>
  )
  return (
    <>
      {list.map((ele, index) => Pair(index, ele))}
      {disabled
        ? null
        : (
        <Button type="dashed" block onClick={() => push({})}>
          + 添加
        </Button>
          )}
    </>
  )
}

export default forwardRef(DynamicKeyValuePairs)
